#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include "UdpServer.hpp"

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << ", port[1024+]" << std::endl;
}

std::string Handler(const std::string& str)
{   
    std::string res = "Server a message: ";
    res += str;
    std::cout << res << std::endl;

    return res;
}

// 指令处理
bool SafeCheck(const std::string &cmd)
{
    std::vector<std::string> v = {"mv", "cp", "git", "su", "top"};
    for(auto& e : v)
    {
        if(cmd.find(e) != std::string::npos)    // 找到啦对应的指令
        {
            return false;
        }
    }
    return true;
}

std::string ExcuteCommand(const std::string& cmd)
{
    std::cout << "get a request cmd: " << cmd << std::endl;
    if(!SafeCheck(cmd))     
    {
        return "The command is prohibited";
    }

    FILE* fp = popen(cmd.c_str(), "r");
    if(fp == nullptr)
    {
        perror("popen");
        return "error";
    }

    // 读取执行的结果
    std::string result;
    char buffer[4096];
    while (true)
    {
        char* ok = fgets(buffer, sizeof(buffer), fp);
        if(ok == nullptr)
            break;
        result += buffer;
    }
    pclose(fp);
    return result;
}

// ./udpserver port
int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    uint16_t port = std::stoi(argv[1]);
    // UdpServer* usvr = new UdpServer(port);
    std::unique_ptr<UdpServer> usvr(new UdpServer(port));
    usvr->Init();
    // usvr->Run(Handler);
    // usvr->Run(ExcuteCommand);
    usvr->Run();
    return 0;
}